package service

import (
	"context"
	"database/sql"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/userInfo/glb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) CreateUsers(ctx context.Context, request *pb.CreateUsersRequest) (*pb.CreateUsersResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.CreateUsersResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager {
		return &pb.CreateUsersResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "用户没有权限",
		}}, nil
	}

	users := make([]models.User, 0, len(request.GetUsers()))
	for _, user := range request.GetUsers() {
		user := models.User{
			AccountID: user.GetAccountID(),
			Name:      sql.NullString{String: user.GetName(), Valid: true},
			Gender:    sql.NullInt32{Int32: user.GetGender(), Valid: true},
			Type:      sql.NullInt32{Int32: user.GetType(), Valid: true},
			IsManager: sql.NullBool{Bool: user.GetIsManager(), Valid: true},
		}
		user.SetPassword(core.StringToMD5(core.DefaultPassword))
		users = append(users, user)
	}

	err = glb.DB.Create(&users).Error
	if err != nil {
		if core.IsDuplicateKeyErr(err) {
			return &pb.CreateUsersResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "某些用户序号已存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return createUsersRespSvrErr, nil
	}

	return &pb.CreateUsersResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
	}, nil
}
